package com.itheima.search.config;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 连接ES
 * @author NicelYHHello
 */
@Configuration
public class EsConfig {

    @Value("${elasticsearch.host:192.168.100.129}")
    private String esHost;

    @Value("${elasticsearch.port:9200}")
    private int esPort;

    @Value("${elasticsearch.scheme:http}")
    private String esScheme;

    @Bean(destroyMethod = "close")
    public RestClient restClient() {
        // 低级客户端创建
        return RestClient.builder(
                new HttpHost(esHost, esPort, esScheme)
        ).build();
    }

    @Bean
    public ObjectMapper objectMapper() {
        // ObjectMapper配置
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        return objectMapper;
    }

    @Bean
    public ElasticsearchTransport elasticsearchTransport(RestClient restClient, ObjectMapper objectMapper) {
        // 传输层创建
        return new RestClientTransport(
                restClient, new JacksonJsonpMapper(objectMapper)
        );
    }

    @Bean
    public ElasticsearchClient elasticsearchClient(ElasticsearchTransport transport) {
        // API客户端创建
        return new ElasticsearchClient(transport);
    }
}
